package com.cyberstep.onstage.audio;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.Hashtable;
import com.jogamp.openal.sound3d.AudioSystem3D;
import com.jogamp.openal.sound3d.Buffer;
import com.jogamp.openal.sound3d.Source;

public class KAudioAL 
implements Audio
{
	class KSound
		implements com.cyberstep.onstage.audio.Sound
	{

		public void play() {
			s.play();
		}

		public void play(int i) {
			s.play();
		}

		public void play(float f, float f1, int i) {
			s.play();
		}

		public void stop() {
			s.stop();
		}

		public void setPitch(float f) {
			s.setPitch(f);
		}

		public void setPan(float f) {
			// TODO Auto-generated method stub
		}

		public void setVolume(float f) {			
			s.setGain(f*masterVolume/10000.0f);
		}

		public float getPitch() {
			return s.getPitch();
		}

		public float getPan() {
			// TODO Auto-generated method stub
			return 0;
		}

		public float getVolume() {
			return s.getGain()*10000.0f/masterVolume;
		}

		public boolean isPlaying() {
			return s.getBuffersProcessed()==0;
		}
		Source s;
		
		KSound(Buffer _b)
		{
			s=AudioSystem3D.generateSource(_b);
		}
	}
	
	public String[] getConditions() {
		return null;
	}

	public void setCondition(int i) {
	}

	public void setMasterVolume(float f) {
		masterVolume=f;
	}

	public float getMasterVolume() {
		return masterVolume;
	}

	public SoundResource getSoundResource(File file) {
		return null;
	}

	public void preBuffer(String s, SoundResource soundresource, int i) {
		Buffer buf = AudioSystem3D.generateBuffers(1)[0];
		
		int t=0;
		if(soundresource.channel==1 && soundresource.samplebits==8)
			t=Buffer.FORMAT_MONO8;
		else if(soundresource.channel==1 && soundresource.samplebits==16)
			t=Buffer.FORMAT_MONO16;
		else if(soundresource.channel==2 && soundresource.samplebits==8)
			t=Buffer.FORMAT_STEREO8;
		else if(soundresource.channel==2 && soundresource.samplebits==16)
			t=Buffer.FORMAT_STEREO16;
		
		buf.configure(ByteBuffer.wrap(soundresource.data), t, (int)soundresource.freq);
		sndsrcs.put(s, buf);
	}

	public Sound getSound(String s, SoundResource soundresource) {
		Buffer buf = (Buffer)sndsrcs.get(s);
		if(buf == null)
		{
			preBuffer(s, soundresource, 1);
			buf = (Buffer)sndsrcs.get(s);
		}
		
		KSound ks = new KSound(buf);
		return ks;
	}

	float masterVolume;
	Hashtable sndsrcs = new Hashtable();;
	
	static
	{
		AudioSystem3D.init();
		AudioSystem3D.makeContextCurrent(
				AudioSystem3D.createContext(
						AudioSystem3D.openDevice(null)));
	}
}

